package kstech.com.wifitest.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.IBinder;

import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import kstech.com.wifitest.utils.DateUtil;

public class WifiService extends Service {
    private onWIFIChangeListener listener;
    private WifiService service;
    private Timer timer;
    private WifiManager wifiManager;
    private int mWIFIstate;
    private int mLastResult;
    private  int resultLv;
    private ConnectivityManager connmanager;
    private NetworkInfo networkInfo;
    public void setWifiListner(onWIFIChangeListener listener) {
        this.listener = listener;
    }

    public WifiService() {
        service = this;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                connmanager = (ConnectivityManager)getApplicationContext().getSystemService(
                                Context.CONNECTIVITY_SERVICE);
                networkInfo = connmanager.getActiveNetworkInfo();
                if(networkInfo ==null || networkInfo.getState() == NetworkInfo.State.DISCONNECTED){
                    listener.forChart(0);
                }
                mWIFIstate = wifiManager.getWifiState();

                if(mWIFIstate == WifiManager.WIFI_STATE_ENABLED){
                    WifiInfo info = wifiManager.getConnectionInfo();

                    int strength = info.getRssi();
                    int speed = info.getLinkSpeed();
                    String units = WifiInfo.LINK_SPEED_UNITS;
                    String ssid = info.getSSID();
                    if(listener!=null)
                    listener.statuesChanged("当前连接状态 ssid-"+ssid+" speed-"+speed+" units-"+ units);


                    if(mLastResult != resultLv){
                        write("当前连接状态 ssid-"+ssid+" speed-"+speed+" units-"+ units);
                    }
                    List<ScanResult> results = wifiManager.getScanResults();
                    for (ScanResult result : results) {

                        if(info.getSSID().equals("\""+result.SSID+"\"")){
                            resultLv = WifiManager.calculateSignalLevel(result.level, 100);
                            //Log.e("qwerqwer",resultLv+"");
                            if(listener!=null)
                            listener.signalChanged(result.SSID,resultLv);
                            if(listener!=null)
                            listener.forChart(resultLv);
                            if(mLastResult != resultLv){
                                write(result.SSID+" 强度："+resultLv+mLastResult);
                            }
                        }
                    }
                }else{
                    if(mWIFIstate == WifiManager.WIFI_STATE_DISABLED){
                        listener.statuesChanged("WIFI_STATE_DISABLED");
                        if(mLastResult != resultLv){
                            write("WIFI_STATE_DISABLED");
                        }
                    }
                }
                mLastResult = resultLv;
            }
        },1000,1000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }
    public interface onWIFIChangeListener{
        void signalChanged(String wifissid,int progress);
        void statuesChanged(String status);
        void forChart(int progress);
    }

    @Override
    public void onDestroy() {
        timer.cancel();
    }

    public void write(String str){
        try {
            //将crash log写入文件
            FileOutputStream fileOutputStream = new FileOutputStream("/storage/sdcard1/wifi_log.txt", true);
            PrintStream printStream = new PrintStream(fileOutputStream);
            printStream.println(DateUtil.getDateTimeFormat(new Date())+"---------------------------------------------");
            printStream.println(DateUtil.getDateTimeFormat(new Date())+"WIFI:  "+str);
            printStream.flush();
            printStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopTimer(){
        timer.cancel();
    }

    public class MyBinder extends Binder{
        public WifiService getService(){
            return service;
        }
    }
}
